package leetcode.code0805;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public boolean splitArraySameAverage(int[] nums) {
		int len = nums.length;
		if (len == 1)
			return false;
		int sum = Arrays.stream(nums).sum();
		for (int i = 0; i < nums.length; i++) {
			nums[i] = nums[i] * len - sum;
		}
		int[] a1 = Arrays.copyOfRange(nums, 0, len >> 1);
		int[] a2 = Arrays.copyOfRange(nums, len >> 1, len);
		Set<Integer> n1 = this.f(a1);
		Set<Integer> n2 = this.f(a2);
		if (n1.contains(0) || n2.contains(0)) {
			return true;
		}
		int s1 = Arrays.stream(a1).sum();
		for (int n : n1) {
			if (n2.contains(-n) && n != s1) {
				return true;
			}
		}
		return false;
	}

	private Set<Integer> f(int[] arr) {
		int len = arr.length;
		int range = 1 << len;
		Set<Integer> ans = new HashSet<>();
		for (int i = 1; i < range; i++) {
			int sum = 0;
			for (int j = 0; j < len; j++) {
				if ((i & (1 << j)) != 0) {
					sum += arr[j];
				}
			}
			ans.add(sum);
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(false, this.splitArraySameAverage(H.str2array3("[0]")));
//		H.compare(true, this.splitArraySameAverage(H.str2array3("[18,0,16,2]")));
//		H.compare(true, this.splitArraySameAverage(H.str2array3("[1,2,3,4,5,6,7,8]")));
//		H.compare(false, this.splitArraySameAverage(H.str2array3("[7,0,16,11,10,9,10,9,8]")));
//		H.compare(false, this.splitArraySameAverage(H.str2array3("[6,8,18,3,1]")));
		H.compare(false, this.splitArraySameAverage(H.str2array3("[3,1]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
